<template>
	<div style="width: 100%;display: flex">
		<div style="border: 1px solid #e7e6e6; width: 100%">
			<div style="position: relative" :style="{ height: clientHeight - 260 + 'px' }">
				<LivePlayer live hideLiveText :videoUrl="videoUrl" :waterMark="osd" @ended="onDeviceVideoEnd"
					@error="onVideoError" @timeupdate="onDeviceVideoTimeUpdate" @media_info="onMediaInfo" v-loading="loading"
					element-loading-text="加载中..." element-loading-background="#000" style="width: 100%; background: #000000"
					aspect='fullscreen'></LivePlayer>
			</div>
			<div class="operateBox">
				<div>
					<!--          <el-button @click="PlaySlow()">-->
					<!--            <el-image class="image" src="/videox/rewind-back.png"></el-image>-->
					<!--          </el-button>-->

					<!--          <el-button @click="PauseResume()">-->
					<!--            <el-image class="image" v-if="PauseResumeSta" src="/videox/play.png"></el-image>-->
					<!--            <el-image class="image" v-else src="/videox/pause.png"></el-image>-->
					<!--          </el-button>-->

					<!--          <el-button @click="PlayFast()">-->
					<!--            <el-image class="image" src="/videox/rewind-forward.png"></el-image>-->
					<!--          </el-button>-->
				</div>
			</div>
		</div>
		<div class="right-box">
			<!--        <div style="background-color: rgb(10, 61, 82); color: rgb(18, 219, 242); padding: 7px 6px; font-size: 16px; margin-bottom: 10px">录像播放</div>-->
			<!--      <div class="block">-->
			<calendar :forbidDate="getCurrentDate()" @dayhandle="dayhandle"></calendar>
			<!--      </div>-->
			<button @click="dialogTableVisible = true">下载</button>
			<div style="text-align: center; margin-top: 10px">
				<el-button type="primary" style="width: 50%" @click="playRecordSearch()">
					<el-icon>
						<Search />
					</el-icon>
					{{ $t("query") }}
				</el-button>
			</div>
		</div>
	</div>

	<div>
		<TimeRule ref="timeRule" :videos="videos" :start="start" :end="end" :minutesPerUnit="minutesPerUnit"
			@timeChange="onTimeChange" v-loading="loadingRecords"></TimeRule>
	</div>

	<el-dialog v-model="dialogTableVisible" title="录像下载" width="30%">
		<p style="text-align: center">选择时间段</p>
		<div style="display: flex;justify-content: center">
			<el-time-picker v-model="downloadTime" value-format="HH:mm:ss" size="large" is-range range-separator="To"
				start-placeholder="Start time" end-placeholder="End time" />
		</div>

		<template #footer>
			<div class="dialog-footer">
				<el-button @click="dialogTableVisible = false">{{ $t("cancel") }}</el-button>
				<el-button @click="downloadlive()">{{ $t("confirm") }}</el-button>
			</div>
		</template>
	</el-dialog>

	<PlaybackDownloadDlg ref="playbackDownloadDlg" @download="onDownload"></PlaybackDownloadDlg>
</template>

<style>
	.operateBox {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 4px 1px;
		margin-bottom: 4px;
	}

	.image {
		width: 20px;
		height: 20px;
	}

	.right-box {
		width: 500px;
		padding-left: 20px;
	}
</style>

<script>
	import useView from "@/hooks/useView";
	import {
		defineComponent,
		reactive,
		toRefs
	} from "vue";
	import elementResizeDetectorMaker from "element-resize-detector";
	import Calendar from "@/components/calendar/calendar.vue";
	import {
		ElMessage
	} from "element-plus";
	import LivePlayer from "@liveqing/liveplayer-v3";
	import TimeRule from '@/views/historyVideo/components/TimeRule.vue'
	import moment from "moment"
	import playbackDownloadDlg from "@/views/historyVideo/components/PlaybackDownloadDlg.vue";

	// 获取当前时间 天  格式“YYYY-MM-DD”
	const getCurrentDate = () => {
		const now = new Date();
		const year = now.getFullYear();
		const month = String(now.getMonth() + 1).padStart(2, "0");
		const day = String(now.getDate()).padStart(2, "0");
		return `${year}-${month}-${day}`;
	};

	// 获取当前时间 时  格式“YYYY-MM-DD HH:mm:ss”
	const getCurrentDateTime = () => {
		const date = new Date();
		const year = date.getFullYear();
		const month = (date.getMonth() + 1).toString().padStart(2, "0");
		const day = date.getDate().toString().padStart(2, "0");
		const hours = date.getHours().toString().padStart(2, "0");
		const minutes = date.getMinutes().toString().padStart(2, "0");
		const seconds = date.getSeconds().toString().padStart(2, "0");
		return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
	};

	// 获取链接呢路径size的参数值
	const gainSize = (url) => {
		let sizeMatch = url.match(/size=(\d+)/);
		console.log(sizeMatch[1]);
		return sizeMatch[1] / 1024 / 1024;
	};

	// 时间格式化
	const convertISOToLocalDate = (isoString) => {
		// 解析ISO 8601字符串为Date对象
		const date = new Date(isoString);
		// 提取年、月、日、时、分、秒
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, "0");
		const day = String(date.getDate()).padStart(2, "0");
		const hours = String(date.getHours()).padStart(2, "0");
		const minutes = String(date.getMinutes()).padStart(2, "0");
		const seconds = String(date.getSeconds()).padStart(2, "0");
		// 格式化日期时间为YYYY-MM-DD HH:mm:ss
		return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
	};

	// 下载
	function downloadFile(url, fileName) {
		const a = document.createElement('a');
		a.style.display = 'none';
		a.href = url;
		a.download = fileName;
		document.body.appendChild(a);
		a.click();
		document.body.removeChild(a);
	}

	export default defineComponent({
		components: {
			LivePlayer,
			Calendar,
			TimeRule,
			playbackDownloadDlg
		},
		props: {
			treeLoading: false,
			option: {}
		},
		setup() {
			const state = reactive({
				getCurrentDate,
				convertISOToLocalDate,
				gainSize,
				clientHeight: document.body.clientHeight,

				// 下载
				dialogTableVisible: false,
				pictureDate: [],
				dataForm: {
					startTime: "",
					endTime: ""
				},

				nowTime: null,

				cameraData: {},

				videoUrl: "",
				records: [],
				videos: [],
				start: 0,
				end: 0,
				minutesPerUnit: 1,
				osd: "",
				streamID: "",
				protocol: "",
				mediaInfo: null,

				loading: false,

				loadingRecords: false,

				day: moment().format('YYYYMMDD'),
				timerange: [
					moment(moment().format('YYYYMMDD'), "YYYYMMDD").startOf('hour').toDate(),
					moment(moment().format('YYYYMMDD'), "YYYYMMDD").startOf('hour').toDate()
				],

				downloadDay: "",
				downloadTime: []
			});

			return {
				...useView(state),
				...toRefs(state)
			};
		},
		watch: {
			// 下载查询时间
			pictureDate: {
				handler(val) {
					if (val === null) {
						this.dataForm.startTime = "";
						this.dataForm.endTime = "";
					} else {
						this.dataForm.startTime = val[0];
						this.dataForm.endTime = val[1];
					}
				},
				deep: true
			}
		},
		created() {
			this.pictureDate = [getCurrentDate() + "T00:00:00", getCurrentDateTime()];
			this.downloadDay = getCurrentDate();
		},
		async mounted() {
			var serverInfo = await this.getServerInfo();
			this.protocol = this.$getQueryString("protocol", serverInfo.PreferStreamFmt || "");
			var start = this.$getQueryString("start", "0");
			if (start) {
				this.start = parseInt(start) || 0;
				if (this.start < 0) {
					this.start = 0;
				}
				if (this.start > 1439) {
					this.start = 1439;
				}
				if (this.minutes < this.start) {
					this.minutes = this.start;
				}
			}
			var end = this.$getQueryString("end", "0");
			if (end) {
				this.end = parseInt(end) || 0;
				if (this.end < 0) {
					this.end = 0;
				}
				if (this.end > 1439) {
					this.end = 1439;
				}
				if (this.end && this.minutes > this.end) {
					this.minutes = this.end;
				}
			}
			// elementResizeDetectorMaker().listenTo(document.getElementById("divPlugin"), () => {
			//   this.$nextTick(() => {
			//     // 监听到事件后执行的业务逻辑
			//     let elementById = document.getElementById("divPlugin");
			//     const rect = elementById.getBoundingClientRect();
			//     if (WebVideoCtrl.I_Resize != null) {
			//       WebVideoCtrl.I_Resize(rect.width, rect.height);
			//     }
			//   });
			// });
		},
		methods: {
			// 获取录像下载地址
			downloadlive() {
				console.log(this.downloadDay)
				console.log(this.downloadTime)
				$.ajax({
					method: "GET",
					// url: `${this.$store.state.apiUrl}/api/v1/playback/recordlist?token=${this.$store.state.accessToken}`,
					url: `http://192.168.0.9:10000/api/v1/playback/start`,
					global: false,
					data: {
						timeout: 5,
						serial: '34020000001110000001',
						code: '34020000001310000012',
						download: true,
						starttime: this.downloadDay + "T" + this.downloadTime[0],
						endtime: this.downloadDay + "T" + this.downloadTime[1],
						token: this.$store.state.accessToken,
					}
				}).then(ret => {
					console.log(ret)
					downloadFile(ret.PlaybackFileURL, ret.ChannelName + "-" + ret.StartAt);
					this.dialogTableVisible = false;
				}).always(() => {});
			},
			dayhandle(day) {
				console.log(day)
				this.downloadDay = day;
				if (day == getCurrentDate()) {
					this.pictureDate = [day + "T00:00:00", getCurrentDateTime()];
				} else {
					this.pictureDate = [day + "T00:00:00", day + "T23:59:59"];
				}
				this.timerange = [day + "T00:00:00", day + "T23:59:59"];
			},
			getServerInfo({
				commit
			}) {
				return new Promise((resolve, reject) => {
					$.ajax({
						method: "GET",
						global: false,
						url: "/api/v1/getserverinfo",
					}).then(serverInfo => {
						try {
							if (serverInfo.ServerTime) {
								var stime = moment(serverInfo.ServerTime, "YYYY-MM-DD HH:mm:ss");
								serverInfo.DiffDuration = moment.duration(stime.diff(moment()));
							}
							resolve(serverInfo);
							return
						} catch (error) {
							console.log(error);
						}
						resolve({});
					}).fail(() => {
						resolve({});
					})
				})
			},
			$getQueryString(name, defVal = "") {
				var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
				var r = window.location.search.substr(1).match(reg);
				if (r != null) {
					return decodeURIComponent(r[2]);
				}
				return defVal;
			},
			isIE() {
				return !!window.ActiveXObject || "ActiveXObject" in window;
			},
			flvSupported() {
				return videojs.browser.IE_VERSION || (flvjs.getFeatureList() && flvjs.getFeatureList().mseLiveFlvPlayback);
			},
			onDeviceVideoEnd() {
				this.mediaInfo = null;
			},
			onDeviceVideoTimeUpdate(t) {
				if (t < 1 || !this.video) return;
				var startTime = moment(this.video.StartTime, 'YYYY-MM-DDTHH:mm:ss');
				startTime.add(t, 'seconds');
				var n = startTime.diff(startTime.clone().startOf('day'), 'minutes');
				this.$refs['timeRule'].clickMinute(n, false);
				var endTime = moment(this.video.EndTime, "YYYY-MM-DDTHH:mm:ss");
				var d = endTime.diff(startTime, 'seconds');
				if (d - t < 3 && !this.switchTimer) { // switch to next video
					this.switchTimer = setTimeout(() => {
						endTime.add(5, 'minutes');
						var n = endTime.diff(endTime.clone().startOf('day'), 'minutes');
						this.$refs['timeRule'].clickMinute(n);
					}, 3000);
				}
			},
			onMediaInfo(mi) {
				this.mediaInfo = mi;
			},
			onVideoError(e) {
				if (e == 'MediaError' && ((this.mediaInfo && String(this.mediaInfo.videoCodec).startsWith("hvc")) || this
						.type == "cloud" || this.protocol == "HLS")) {
					console.log("提示: 正在播放 H265 直出流, 确保浏览器版本较新, 并且开启硬件加速");
					return
				}
				if (!this.video) return;
				var endTime = moment(this.video.EndTime, "YYYY-MM-DDTHH:mm:ss");
				endTime.add(5, 'minutes');
				var n = endTime.diff(endTime.clone().startOf('day'), 'minutes');
				this.$refs['timeRule'].clickMinute(n);
			},
			getDeviceRecords(refresh) {
				// if(!this.serial || !this.code) return;
				console.log(refresh);
				if (refresh) {
					this.loadingRecords = true;
					this.records = [];
				}
				console.log(this.nextTimeRange())
				if (!this.nextTimeRange()) {
					this.videos = this.records;
					this.loadingRecords = false;
					return
				}

				$.ajax({
					method: "GET",
					// url: `${this.$store.state.apiUrl}/api/v1/playback/recordlist?token=${this.$store.state.accessToken}`,
					url: `http://192.168.0.9:10000/api/v1/playback/recordlist`,
					global: false,
					data: {
						timeout: 5,
						serial: '34020000001110000001',
						code: '34020000001310000012',
						// serial: this.cameraData.gbsCode,
						// code: this.cameraData.gbsCode,
						// center: this.center,
						// indistinct: this.indistinct,
						starttime: this.dataForm.startTime,
						endtime: this.dataForm.endTime,
						token: this.$store.state.accessToken,
					}
				}).then(ret => {
					var items = ret.RecordList || [];
					this.records = this.records.concat(items.filter(item => {
						if (!item || !item.StartTime || !item.EndTime) {
							return false;
						}
						if (this.records.some(v => (v.StartTime === item.StartTime && v.EndTime === item.EndTime))) {
							console.log("repeat", item.StartTime, "~", item.EndTime);
							return false;
						}
						return true;
					}));
				}).always(() => {
					this.$nextTick(() => {
						this.getDeviceRecords(false);
					})
				});
			},
			nextTimeRange() {
				console.log("jijiji=-----", this.timerange);
				var end = moment(this.day, "YYYYMMDD").endOf('day');
				var now = moment().startOf("second");
				if (end.isAfter(now, "second")) {
					end = now;
				}
				var r1 = moment(this.timerange[1]);
				if (r1.isSameOrAfter(end, "second")) {
					return false;
				}
				var r2 = moment(this.timerange[1]).add(6, 'hours');
				if (r2.isAfter(end)) {
					r2 = end;
				}
				if (r2.clone().startOf("minute").isSameOrBefore(r1.clone().startOf("minute"), "second")) {
					return false;
				}
				console.log(r1.format("YY-MM-DD HH:mm:ss"), "~", r2.format("YY-MM-DD HH:mm:ss"), "loading...");
				this.timerange = [r1.toDate(), r2.toDate()];
				return true;
			},
			onTimeChange(video) {
				console.log(video);
				// if (this.type == 'device' && video != this.video) {
				this.video = video;
				if (video) {
					this.startPlayback();
				} else {
					this.stopPlayback();
				}
				// }
			},
			// 减速
			PlaySlow() {
				let oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex);
				if (oWndInfo == null) {
					ElMessage.error(" 暂无设备播放，请先选择设备！");
					return;
				}
				WebVideoCtrl.I_PlaySlow();
			},
			// 加速
			PlayFast() {
				let oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex);
				if (oWndInfo == null) {
					ElMessage.error(" 暂无设备播放，请先选择设备！");
					return;
				}
				WebVideoCtrl.I_PlayFast();
			},
			playRecordSearch() {
				this.getDeviceRecords(false);
			},
			async startPlayback() {
				if (!this.video) return;
				this.loading = true;
				await this.stopPlayback();
				$.get("http://192.168.0.9:10000/api/v1/playback/start", {
					serial: '34020000001110000001',
					code: '34020000001310000012',
					// serial: this.serial,
					// code: this.code,
					starttime: this.video.StartTime,
					endtime: this.video.EndTime,
					token: this.$store.state.accessToken,
				}).then(streamInfo => {
					var protocol = "HLS";
					var videoUrl = streamInfo.HLS;
					if (this.flvSupported()) {
						videoUrl = this.isIE() ? streamInfo.WS_FLV : streamInfo.FLV;
						protocol = this.isIE() ? "WS_FLV" : "FLV";
					}
					switch (String(this.protocol).toUpperCase()) {
						case "WEBRTC":
							if (this.rtcSupported()) {
								videoUrl = streamInfo.WEBRTC;
								protocol = "WEBRTC";
							}
							break;
						case "FLV":
							if (this.flvSupported() && !this.isIE()) {
								videoUrl = streamInfo.FLV;
								protocol = "FLV";
							}
							break;
						case "WS_FLV":
						case "WS-FLV":
							if (this.flvSupported()) {
								videoUrl = streamInfo.WS_FLV;
								protocol = "WS_FLV";
							}
							break;
						case "HLS":
							videoUrl = streamInfo.HLS;
							protocol = "HLS";
							break;
						case "RTMP":
							videoUrl = streamInfo.RTMP;
							protocol = "RTMP";
							break;
					}
					this.streamID = streamInfo.StreamID;
					this.osd = this.osd || streamInfo.ChannelOSD || "";
					this.protocol = protocol;
					this.videoUrl = videoUrl;
					console.log("videourl---", this.videoUrl)
					if (this.speed > 0 && this.speed != 1) {
						this.scaleOnStart();
					}
				}).always(() => {
					this.loading = false;
				});
			},
			stopPlayback() {
				return new Promise((resolve, reject) => {
					if (this.switchTimer) {
						clearTimeout(this.switchTimer);
						this.switchTimer = 0;
					}
					this.videoUrl = "";
					if (!this.streamID) {
						resolve();
						return
					}
					$.ajax({
						method: "GET",
						url: "/api/v1/playback/stop",
						global: false,
						data: {
							streamid: this.streamID,
							token: this.$store.state.accessToken,
						}
					}).always(() => {
						this.streamID = "";
						// this.mediaInfo = null;
						resolve();
					})
				})
			},
			onDownload() {
				this.streamID = "";
			}
		}
	});
</script>